import * as types from '../store/action-types';
import {put,call} from 'redux-saga/effects';
import {delay} from '../utils';
function readFile(filename,callback){
  setTimeout(function(){
    callback(null,filename);
  },1000)
}
//effects都是函数，函数都要执行后返回一个纯对象,这些对象相当于是发给saga中间件的指令
export function* incrementAsync(){
    //yield  delay(1000); //await promise完成
    //let result =yield call([{name:'zhufeng'},delay],1000,'zf');//调用  fn.call
    //yield apply({name:'zhufeng'},delay,[1000,'zf']);
    //let result = yield cps(readFile,'README.md');
    //console.log('incrementAsync result',result);
    //put表示向仓库派发一个动作 dispatch({type:types.INCREMENT});
    //apply: argument of type [context, fn] has undefined or null
    //用try catch捕获处理
    /* try{
        yield call(delay,1000);
        yield put({type:types.INCREMENT});
        alert('成功');
    }catch(error){
        alert('失败');
    } */
    /**
    let {code,data} = yield call(delay,1000);
    if(code == 0){
        yield put({type:types.INCREMENT});
        alert('成功');
    }else{
        alert('失败');
    }
    */
   yield call(delay,1000);
   yield put({type:types.INCREMENT});
}
//saga 监听者 watcher 工作者worker  root
export default function* watchIncrement(){
   //它负责监听每一个INCREMENT_SAGA动作，当这个动作派发了，就会执行对应的Generator incrementAsync
   //yield takeEvery(types.INCREMENT_SAGA,incrementAsync);
   //yield takeLatest(types.INCREMENT_SAGA,incrementAsync);
   /**
   while(true){
       //监听一次action,当监听到之后就往下执行
    let action = yield take(types.INCREMENT_SAGA);
    console.log(action)
    yield put({type:types.INCREMENT});
   }
    */
   /* for(let i=0;i<3;i++){
    let action = yield take(types.INCREMENT_SAGA);
    yield put({type:types.INCREMENT});
   } */
   for(let i=0;i<3;i++){
       //takeEvery 它其实是开启了一个线程，单开了一个任务，并不会阻塞不当前任务
      //yield takeEvery(types.INCREMENT_SAGA,incrementAsync);
      //console.log(i);
   }
}